﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entity;

namespace School.SystemManage.WebPages.Ads
{
    public partial class AdsList : Base.PermissionBasePage
    {
        TechnologySchoolEntities db = new TechnologySchoolEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            var ads = from a in db.Ad
                      orderby a.UploadTime descending
                      select new
                      {
                          a.Aid,
                          a.ImgPath,
                          a.Url,
                          a.UploadTime
                      };
            lvAds.DataSource = ads;
            lvAds.DataBind();
        }

        protected void lvAds_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            lvAds.EditIndex = e.NewEditIndex;
            BindData();
        }

        protected void lvAds_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            FileUpload upload = (FileUpload)lvAds.Items[e.ItemIndex].FindControl("fileUpload");
            string imgPath = string.Empty;

            int keyid = (int)lvAds.DataKeys[e.ItemIndex].Value;
            string url = ((TextBox)lvAds.Items[e.ItemIndex].FindControl("txbUrl")).Text;
            Ad ad = db.Ad.FirstOrDefault(a => a.Aid == keyid);
            try
            {
                if (upload.HasFile)
                {
                    if (UploadImg(upload, out imgPath))
                    {
                        ad.ImgPath = imgPath;
                    }
                    else
                    {
                        lvAds.EditIndex = -1;
                        BindData();
                        lblMsg.Text = "上传图片失败！";

                        return;
                    }
                }

                ad.Url = url;
                ad.UploadTime = DateTime.Now;

                if (db.SaveChanges() > 0)
                {
                    lvAds.EditIndex = -1;
                    BindData();
                }
                else
                {
                    lblMsg.Text = "更新失败！";
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "更新发生异常，原因：" + ex.Message;
            }
        }

        protected void lvAds_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            if (e.CancelMode == ListViewCancelMode.CancelingEdit)
            {
                lvAds.EditIndex = -1;
                BindData();
            }
        }

        protected void lvAds_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            int keyid = (int)lvAds.DataKeys[e.ItemIndex].Value;
            Ad ad = db.Ad.FirstOrDefault(a => a.Aid == keyid);

            db.DeleteObject(ad);
            db.SaveChanges();
            BindData();
        }

        private bool UploadImg(FileUpload upload, out string imagePath)
        {
            imagePath = string.Empty;
            if (upload.FileContent.Length > 0)
            {
                string originalFileName = upload.FileName;
                string extendName = originalFileName.Substring(originalFileName.LastIndexOf('.') + 1);
                string newFileName = Guid.NewGuid().ToString() + "." + extendName;
                string serverSavePath = Server.MapPath(@"~\UploadFiles\ads");
                imagePath = System.IO.Path.Combine(@"\UploadFiles\ads", newFileName);
                upload.SaveAs(System.IO.Path.Combine(serverSavePath, newFileName));

                return true;
            }
            return false;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string imgPath = string.Empty;
            try
            {
                if (addUpload.HasFile)
                {
                    if (UploadImg(addUpload, out imgPath))
                    {
                        Ad ad = new Ad();
                        ad.ImgPath = imgPath;
                        ad.IsInnerLink = rbtLink.SelectedValue == "1";
                        ad.Url = txbAddUrl.Text.Trim();
                        ad.Content = editor.Value;
                        ad.UploadTime = DateTime.Now;

                        db.AddToAd(ad);
                        db.SaveChanges();

                        BindData();
                    }
                    else
                    {
                        lblMsg.Text = "上传图片失败！";
                    }
                }
                else
                {
                    lblMsg.Text = "请选择要上传的图片！";
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "添加失败，原因：" + ex.Message;
            }

        }

        #region 操作权限控制

        public override void SetEditDisable()
        {
            base.SetEditDisable();

            foreach (ListViewDataItem item in lvAds.Items)
            {
                if (item.ItemType == ListViewItemType.DataItem)
                {
                    LinkButton linkEdit = (LinkButton)item.FindControl("LinkButton1");
                    LinkButton linkDelete = (LinkButton)item.FindControl("LinkButton3");
                    linkEdit.Visible = false;
                    linkDelete.Visible = false;
                }
            }
            addTable.Visible = false;
        }

        public override void SetReviewDisable()
        {
            base.SetReviewDisable();
        }

        public override void SetViewDisable()
        {
            base.SetViewDisable();
        }

        #endregion
    }
}
